package dk.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ReturnData.ResponseData;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.lang.UUID;
import dk.Utils.COSUtils;
import dk.Utils.POIUtils;
import dk.Utils.SpringContextUtils;
import dk.beans.Examlist;
import dk.beans.studentexamlist;
import dk.beans.subject;
import dk.beans.EasyPoiExcelBean.ExamBean;
import dk.mapper.StudentExamListMapper;
import dk.mapper.StudentMapper;
import dk.mapper.examlistmapper;
import dk.mapper.subjectmapper;

@RestController

public class ExamListController {
@Autowired
examlistmapper examlistmapper;
@Autowired
subjectmapper subjectmapper;
@Autowired
StudentExamListMapper studentexamlistmapper;
//得到所有题目信息
@RequestMapping("/GetExamList")
public ResponseData GetExamList() {
	
	ResponseData data = new ResponseData();
	List<Examlist> list = examlistmapper.selectList(null);
	//由于subjectname也就是科目名字 非数据库字段 所以我们需要再次取subject表中查询
	for(Examlist examlist : list) {
		QueryWrapper<subject> qw = new QueryWrapper<subject>();
		subject subject = subjectmapper.selectOne(qw.eq("id", examlist.getSubjectid()));
		examlist.setSubjectname(subject.getName());
	}
	
	data.setCode(200);
	data.setMessage("获取信息成功");
	data.setData(list);
	return data;
	
}
@RequestMapping("/AddExamList")
public ResponseData AddExamList(Examlist examlist) {
	System.out.println("/AddExamList");
	System.out.println(examlist);
	
	ResponseData data = new ResponseData();
	
	
	if(!examlist.equals(null)) {
		examlistmapper.insert(examlist);
		data.setCode(200);
		data.setMessage("添加成功");
		
		
	}
	else {
		data.setCode(201);
		data.setMessage("添加失败");
		
	}
	
	
	return data;
}
@RequestMapping("/SearchExamlistBySubjectName")
public ResponseData SearchBySubjectId(String subjectname) {
	ResponseData data = new ResponseData();
	//获取到subjectname 去数据库查询
	QueryWrapper<subject> queryWrapper = new QueryWrapper<subject>();
	//queryWrapper.eq("name",subjectname);
	queryWrapper.like("name", subjectname);
	List<subject> list = subjectmapper.selectList(queryWrapper);
	List<Examlist> Examlist = new ArrayList<Examlist>();
	//得到id查询
	for(subject subject :list) {
		int id = subject.getId();
		QueryWrapper<Examlist> queryWrapper2 = new QueryWrapper<Examlist>();
		queryWrapper2.eq("subjectid",id);
		List<Examlist> dbExamlist =examlistmapper.selectList(queryWrapper2);
		for(Examlist examlist:dbExamlist) {
			examlist.setSubjectname(subject.getName());
			Examlist.add(examlist);
		}
	}
	if(Examlist.size()>0) {
		data.setCode(200);
		data.setMessage("按条件查询examlist成功");
		data.setData(Examlist);
	}
	else {
		data.setCode(201);
		data.setMessage("无数据");
		data.setData(Examlist);
	}
	
	
	return data;
	
	
}
@RequestMapping("/SearchExamListByExamListTitle")
public ResponseData SearchByExamListTitle(String ExamListTitle) {
	ResponseData data = new ResponseData();
	QueryWrapper<Examlist> queryWrapper2 = new QueryWrapper<Examlist>();
	queryWrapper2.like("title", ExamListTitle);
	List<Examlist> Examlist =examlistmapper.selectList(queryWrapper2);
	for(Examlist examlist : Examlist) {
		QueryWrapper<subject> qw = new QueryWrapper<subject>();
		subject subject = subjectmapper.selectOne(qw.eq("id", examlist.getSubjectid()));
		examlist.setSubjectname(subject.getName());
	}
	data.setCode(200);
	data.setMessage("按条件查询examlist成功");
	data.setData(Examlist);
	return data;
	
}
//分页api
@RequestMapping("SearchExamListByPage")
public ResponseData SearchByPage(Integer pagenum,Integer count){
	ResponseData data = new ResponseData();
	IPage<Examlist> userPage = new Page<>(pagenum, count);//参数一是当前页，参数二是每页个数
	userPage = examlistmapper.selectPage(userPage, null);
	
	//查询完遍历输出
	
	List<Examlist> list = userPage.getRecords();
	for(Examlist examlist : list) {
		QueryWrapper<subject> qw = new QueryWrapper<subject>();
		subject subject = subjectmapper.selectOne(qw.eq("id", examlist.getSubjectid()));
		examlist.setSubjectname(subject.getName());
	}
	data.setCode(200);
	data.setMessage("按分页条件查询examlist成功");
	data.setData(list);
	
	return data;
}
//通过id获取examlist信息
@RequestMapping("/GetExamListById")
public ResponseData GetExamListById(Integer id) {
	ResponseData data = new ResponseData();
	QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
	qw.eq("id", id);
	Examlist examlist = examlistmapper.selectOne(qw);
	data.setCode(200);
	data.setMessage("通过id查询数据成功");
	data.setData(examlist);
	return data;
}
//更新api
@RequestMapping("/UpdateExamListById")
public ResponseData UpdateExamlist(Examlist examlist) {
	System.out.println("修改开始了");
	ResponseData data = new ResponseData();
	QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
	System.out.println(examlist);
	examlistmapper.update(examlist,qw.eq("id", examlist.getId()));
	data.setCode(200);
	data.setMessage("修改成功");
	data.setData(null); 
	System.out.println("修改结束了");
	return data;
}
//删除api
@RequestMapping("DeleteExamListByid")
public ResponseData DeleteExamListByid(Integer id) {
	ResponseData data = new ResponseData();
	QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
	qw.eq("id", id);
	examlistmapper.delete(qw);
	data.setCode(200);
	data.setMessage("删除成功");
	return data;
	
}
//Echarts api
@RequestMapping("GetExamListEchart")
public ResponseData GetExamListEchart() {
	ResponseData data = new ResponseData();
	List<Map> list = new ArrayList<Map>();
	//此处查出信息 每颗星占多少
	for(int i =1;i<6;i++) {
		QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
		qw.eq("difficulty",i);
		int count = examlistmapper.selectCount(qw);
		Map map1 = new HashMap();
		
		map1.put("value",count);
		map1.put("name",i+"星");
		list.add(map1);
		
	}
	data.setCode(200);
	data.setData(list);
	data.setMessage("图表信息获取成功");
	return data;
	
	
}
//批量添加 单选
@PostMapping("BatchAddOptionExamList")
public ResponseData BatchAddOptionExamList(@RequestBody String examliststr) throws UnsupportedEncodingException {
	System.out.println("BatchAddOptionExamList");
	ResponseData data = new ResponseData();
	String str = examliststr;
	
	str = StringEscapeUtils.unescapeJava(str);
	str = str.substring(16,str.length()-2);
	System.out.println(str);
	JSONObject jsonObject = JSONObject.parseObject(str);
	JSONArray jsonArray = (JSONArray)jsonObject.get("Examlist");
	List<Examlist> list = (List<Examlist>)JSONArray.parseArray(jsonArray.toString(), Examlist.class);
	
	for(Examlist examlist:list) {
		//根据截取的字符串判断是否含有空 和题目名称是否重复
		//判断为空
		if(StringUtils.isEmpty(examlist.getOptiona())
		 &&StringUtils.isEmpty(examlist.getOptionb())
		 &&StringUtils.isEmpty(examlist.getOptionc())
		 &&StringUtils.isEmpty(examlist.getOptiond())
		 &&StringUtils.isEmpty(examlist.getAnswer())
		 &&StringUtils.isEmpty(examlist.getTitle())
		 &&examlist.getSubjectid().equals(0)
		 &&examlist.getScorce().equals(0)
		 &&examlist.getDifficulty().equals(0)	
				){
			data.setCode(201);
			data.setMessage("题目为"+examlist.getTitle()+"提交结果含有空值");
			return data;
			
		}
		else {
			QueryWrapper<subject> qw = new QueryWrapper<subject>();
			//qw.select("name");
			qw.eq("id", examlist.getSubjectid());
			//查询subjectid是否符合在数据库内
			subject subject = subjectmapper.selectOne(qw);
			if(subject==null) {
				data.setCode(201);
				data.setMessage("名为"+examlist.getTitle()+"没有所属学科,请参照学科表填写");
				return data;
			}
			//字段为空 返回错误信息
			if(StringUtils.isEmpty(subject.getName())) {
				data.setCode(201);
				data.setMessage("名为"+examlist.getTitle()+"没有所属学科,请参照学科表填写");
				return data;
			}
			else {
				examlist.setSubjectname(subject.getName());
				
			}
			
			
			
		}
	}
	for(Examlist list1 : list) {
		//往数据库存
		list1.setType(0);
		examlistmapper.insert(list1);
		data.setCode(200);
		data.setMessage("批量添加成功");
	}
	return data;
}
//批量添加 简答
@PostMapping("BatchAddShortAnswerExamList")
public ResponseData BatchAddShortAnswerExamList(@RequestBody String examliststr) {
	System.out.println("BatchAddOptionExamList");
	ResponseData data = new ResponseData();
	String str = examliststr;
	
	str = StringEscapeUtils.unescapeJava(str);
	str = str.substring(16,str.length()-2);
	System.out.println(str);
	JSONObject jsonObject = JSONObject.parseObject(str);
	JSONArray jsonArray = (JSONArray)jsonObject.get("Examlist");
	List<Examlist> list = (List<Examlist>)JSONArray.parseArray(jsonArray.toString(), Examlist.class);
	
	for(Examlist examlist:list) {
		//声明简答标识符
		examlist.setType(1);
		//根据截取的字符串判断是否含有空 和题目名称是否重复
		//判断为空
		if(
		 StringUtils.isEmpty(examlist.getAnswer())
		 &&StringUtils.isEmpty(examlist.getTitle())
		 &&examlist.getSubjectid().equals(0)
		 &&examlist.getScorce().equals(0)
		 &&examlist.getDifficulty().equals(0)	
				){
			data.setCode(201);
			data.setMessage("题目为"+examlist.getTitle()+"提交结果含有空值");
			return data;
			
		}
		else {
			QueryWrapper<subject> qw = new QueryWrapper<subject>();
			//qw.select("name");
			qw.eq("id", examlist.getSubjectid());
			//查询subjectid是否符合在数据库内
			subject subject = subjectmapper.selectOne(qw);
			if(subject==null) {
				data.setCode(201);
				data.setMessage("名为"+examlist.getTitle()+"没有所属学科,请参照学科表填写");
				return data;
			}
			//字段为空 返回错误信息
			if(StringUtils.isEmpty(subject.getName())) {
				data.setCode(201);
				data.setMessage("名为"+examlist.getTitle()+"没有所属学科,请参照学科表填写");
				return data;
			}
			else {
				examlist.setSubjectname(subject.getName());
				
			}
			
			
			
		}
	}
	for(Examlist list1 : list) {
		//往数据库存
		list1.setType(0);
		examlistmapper.insert(list1);
		data.setCode(200);
		data.setMessage("批量添加成功");
	}
	return data;
}
//生成题目 返回list回显到前端 生成试卷id供前端使用
@PostMapping("GenerateExamList")//暴力破解永远的神！
public ResponseData GenerateExamList(Integer TotalScore,Integer	OptionNum,Integer ShortAnswerNum) throws IOException {
	ResponseData data = new ResponseData();
	//根据分值判断 是否可以生成题库
	if(TotalScore != OptionNum*5 + ShortAnswerNum*10) {
		data.setCode(201);
		data.setMessage("您选择的题目数量有误,请检查");
		return data;
	}
	//根据数据库的题目数量判断是否可以出单选题
	QueryWrapper<Examlist> qw1 = new QueryWrapper<Examlist>();
	qw1.eq("type", 0);
	int OptionExamListCount = examlistmapper.selectCount(qw1);
	if(OptionExamListCount < OptionNum) {
		data.setCode(201);
		data.setMessage("数据库中选择题数量不足,最多可选"+OptionExamListCount);
		return data;
	}
	//根据数据库的题目数量判断是否可以出简答题
	QueryWrapper<Examlist> qw2 = new QueryWrapper<Examlist>();
	qw2.eq("type", 1);
	int ShortAnswerExamListCount = examlistmapper.selectCount(qw2);
	if(ShortAnswerExamListCount<ShortAnswerNum) {
		data.setCode(201);
		data.setMessage("数据库中简答题数量不足,最多可选"+ShortAnswerExamListCount);
		return data;
	}
	//根据分值判断 
	//生成uuid返回给前端
	String uuid = String.valueOf(UUID.fastUUID());
	//因为计算量大 开启另一个线程
	Multithreading mt = new Multithreading();
	mt.setUUid(uuid);
	mt.setShortAnswerExamListCount(ShortAnswerExamListCount);
	
	mt.setOptionNum(OptionNum);
	mt.setTotalScore(TotalScore);
	
	mt.setShortAnswerNum(ShortAnswerNum);
	
	new Thread(mt).start();
	
	data.setCode(200);
	data.setMessage("试卷生产中,请在5分钟后查看");
	data.setData("https://misaka917-1301164487.cos.ap-nanjing.myqcloud.com/examlist/"+uuid+".xls");
			
	
	return data;
}
//学生用拉取题库
@PostMapping("GetExamListByStudent")
//传入参数 学科id 难易度  单选数量 简答数量 回显试卷id 
public ResponseData GetExamListByStudent(Integer Subjectid,Integer OptionExamNum,Integer ShortAnswerExamNum,Integer studentid) {
	ResponseData data = new ResponseData();
	/*
	//查询学科id是否存在题目
	if(examlistmapper.selectCount(new QueryWrapper<Examlist>().eq("subjectid", Subjectid)) <=OptionExamNum) {
		data.setCode(201);
		data.setMessage("数据库所选学科单选题库不足");
		return data;
	}*/
	//获取db的单选和简答数量
	Integer dbOptionNum = examlistmapper.selectCount(new QueryWrapper<Examlist>().eq("type", 0).eq("subjectid", Subjectid));
	Integer dbShortAnswerNum = examlistmapper.selectCount(new QueryWrapper<Examlist>().eq("type", 1).eq("subjectid", Subjectid));
	System.out.println(dbOptionNum);
	System.out.println(dbShortAnswerNum);
	if(dbOptionNum == 0&&dbOptionNum < OptionExamNum) {
		data.setCode(201);
		data.setMessage("数据库单选题库不足");
		return data;
	}
	if(dbShortAnswerNum<ShortAnswerExamNum) {
		data.setCode(201);
		data.setMessage("数据库简答题库不足");
		return data;
	}
	//题库充足
	Set<Integer> set =new HashSet<Integer>();
	//查询数据库的最大id
	QueryWrapper<Examlist> qw11 = new QueryWrapper<Examlist>();
	qw11.orderByDesc("id");
	
	
	//获取到列表
	List<Examlist> examlist = examlistmapper.selectList(qw11);
	Examlist examlist1 = examlist.get(0);
	//声明两个随机数种子
	Random Optionrandom = new Random();
	//简答随机数范围
	Random ShortAnswerrandom = new Random();
	Set<Integer> set1 = new HashSet<Integer>();
	//声明返回用列表
	List<Examlist> reslist = new ArrayList<Examlist>();
	System.out.println(set.size());
	while(set.size() <  OptionExamNum) {
		QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
		int id = Optionrandom.nextInt(examlist1.getId());
		//优化 判断是否在set里
		if(!set.contains(id)) {
			int count = examlistmapper.selectCount(qw.eq("id",id).eq("type", 0));
			if(count!=0) {
				set.add(id);
				//把答案置空
				Examlist examlist2 = examlistmapper.selectOne(qw.eq("id",id));
				//examlist2.setAnswer("  ");
				reslist.add(examlist2);
			}
			
		}
		
		System.out.println("单选id表长度为"+set.size());
	}
	while(set1.size()<ShortAnswerExamNum) {
		QueryWrapper<Examlist> qw = new QueryWrapper<Examlist>();
		int id = ShortAnswerrandom.nextInt(examlist1.getId());
		if(!set1.contains(id)) {
			int count = examlistmapper.selectCount(qw.eq("id",id).eq("type", 1));
			if(count!=0) {
				set1.add(id);
				//把答案置空
				Examlist examlist2 = examlistmapper.selectOne(qw.eq("id",id));
				//examlist2.setAnswer("  ");
				reslist.add(examlist2);
			}
			
		}
		
		System.out.println("简答id表长度为"+set1.size());
	}
	//存进studentexamlist表
	studentexamlist studentexamlist = new studentexamlist();
	//先生成一跳pid = 0的数据
	studentexamlist.setPid(0);
	studentexamlist.setExamlistid(0);
	studentexamlist.setStudentid(studentid);
	studentexamlistmapper.insert(studentexamlist);
	//返回自增主键
	int id = studentexamlist.getId();
	for(Examlist list : reslist) {
		studentexamlist studentexamlist1 = new studentexamlist();
		studentexamlist1.setPid(id);
		studentexamlist1.setExamlistid(list.getId());
		studentexamlist1.setStudentid(studentid);
		studentexamlistmapper.insert(studentexamlist1);
	}
	data.setCode(200);
	data.setMessage("试卷生成成功");
	data.setData(reslist);
	
	return data;
}
//根据试卷id查询题库






}
